using System;
using System.Collections.Generic;
using Churchtoolkit.Utils.BootStrapper;
using Churchtoolkit.Utils.Composit.Configuration;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ServiceLocatorAdapter;

namespace Churchtoolkit.Utils.Composit
{
    public class ModuleInitilizerTask : IBootstrapperTask
    {
        private readonly IUnityContainer _container;
        private readonly List<ModuleInitilizerBase> modules;

        public ModuleInitilizerTask()
        {
            modules = new List<ModuleInitilizerBase>();
            _container = new UnityContainer();
        }

        #region IBootstrapperTask Members

        public void Execute()
        {
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(_container));
            //----------------------------------------------------------------------------------------
            foreach (Module moduleElement in CompositSection.Instance.Modules)
            {
                var module = Activator.CreateInstance(moduleElement.Assembly) as ModuleInitilizerBase;
                RegisterModule(module);

                // module initilization life cycle
                module.OnInitilize();
                module.OnInitilizeContainer(_container);
                module.OnInitilizeServices();
                module.OnInitilizeNavigation();
            }
        }

        #endregion

        private void RegisterModule(ModuleInitilizerBase module)
        {
            modules.Add(module);
        }
    }
}